﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Security;
using System.Xml;
using System;

namespace GoogleAppsTools
{
    class GoogleMailChecker
    {
        // Specify the URL to receive the request.
        public static List<NewMail> CheckForNewMail(string username, SecureString password)
        {
            XmlDocument doc; //the xml document the data is downloaded to
            XmlNodeList entries; //contains the list of nodes called 'entry' in the xml document
            List<NewMail> newMailList = new List<NewMail>(); //the list that will be returned containing all the new mail

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://mail.google.com/mail/feed/atom"); //create the connection object to google

                // Set some reasonable limits on resources used by this request
                request.MaximumAutomaticRedirections = 4;
                request.MaximumResponseHeadersLength = 4;

                // Set credentials to use for this request.
                request.Credentials = new NetworkCredential() { UserName = username, SecurePassword = password };

                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) //connect to the google servers
                {
                    // Retrieve XML document and put it in the XmlDocument object
                    doc = new XmlDocument();
                    doc.Load(response.GetResponseStream());
                }

                entries = doc.GetElementsByTagName("entry"); //get all the nodes with the name 'entry' and put them in a list

                foreach (XmlNode entry in entries) //go through the list and create a newMail object with the info in each node.
                {
                    NewMail email = new NewMail(entry.ChildNodes[0].InnerText.ToString(),
                                                entry.ChildNodes[1].InnerText.ToString(),
                                                entry.ChildNodes[2].Attributes[1].InnerText.ToString(),
                                                entry.ChildNodes[6].ChildNodes[0].InnerText.ToString(),
                                                entry.ChildNodes[6].ChildNodes[1].InnerText.ToString(),
                                                Convert.ToDateTime(entry.ChildNodes[4].InnerText.ToString()));
                    if (email.Title == "")
                        email.Title = "(no title)";
                    newMailList.Add(email); //then add this new object to the list to be returned
                }
            }
            catch (Exception)
            {
                //System.Windows.Forms.MessageBox.Show(ex.ToString());
                //let the main application catch the error
                return null;
            }

            return newMailList; //when done, return the completed list
        }

        /// <summary>
        /// Checks if two list items are the same
        /// </summary>
        private static bool CompareMailItems(NewMail newMailItem, NewMail oldMailItem)
        {

            if (newMailItem.Title == oldMailItem.Title &&
            newMailItem.Summary == oldMailItem.Summary &&
            newMailItem.Link == oldMailItem.Link &&
            newMailItem.SenderName == oldMailItem.SenderName &&
            newMailItem.SenderEmail == oldMailItem.SenderEmail &&
            newMailItem.Received == oldMailItem.Received)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// Checks if two list items are the same
        /// </summary>
        public static bool checkForNewMailSinceLastCheck(List<NewMail> newEmails, List<NewMail> oldEmails)
        {
            if (newEmails == null || oldEmails == null)
                return false;

            if (oldEmails.Count == 0 && newEmails.Count > 0)
                return true;

            if (newEmails.Count > oldEmails.Count)
                return true;

            if (newEmails.Count < oldEmails.Count || newEmails.Count == oldEmails.Count)
            {
                foreach (NewMail newMailItem in newEmails)
                {
                    int count = 0;
                    foreach (NewMail oldMailItem in oldEmails)
                    {

                        if (CompareMailItems(newMailItem, oldMailItem))
                        {
                            //System.Windows.Forms.MessageBox.Show(newMailItem.Title + " = " + oldMailItem.Title);
                            count++;
                        }

                    }
                    if (count == 0)
                        return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Used to check if new bitmaps are required in the taskbar thumbnail.  This is different from above because if there is less emails, then new bitmaps are required to clear the old (read) emails.
        /// </summary>
        /// <param name="newEmails"></param>
        /// <param name="oldEmails"></param>
        /// <returns></returns>
        public static bool checkIfNewBitmapRequired(List<NewMail> newEmails, List<NewMail> oldEmails, bool thumbnailsCreated)
        {
            if (newEmails == null || oldEmails == null)
                return true;

            if (thumbnailsCreated == false)
                return true;

            if (newEmails.Count < oldEmails.Count)
                return true;

            if (newEmails.Count > oldEmails.Count)
                return true;

            if (newEmails.Count == oldEmails.Count)
            {
                foreach (NewMail newMailItem in newEmails)
                {
                    int count = 0;
                    foreach (NewMail oldMailItem in oldEmails)
                    {

                        if (CompareMailItems(newMailItem, oldMailItem))
                        {
                            //System.Windows.Forms.MessageBox.Show(newMailItem.Title + " = " + oldMailItem.Title);
                            count++;
                        }

                    }
                    if (count == 0)
                        return true;
                }
            }
            return false;
        }
    }
}